
import coursewareApi from "@rc/apis/rc/courseware.mjs";
import rcTagApi from "@rc/apis/rc/tag.mjs";
import deleteResource from "../components/delete-resource.vue";//删除资源弹窗
import ccApi from "@rc/apis/cc/index.mjs";

const niceloo = (new Function("return this"))().niceloo;


export default {
    data() {
        return{
            oldCheckState:'' //资源现在的审核状态
        };
    },
    components:{
        deleteResource
    },
    filters: {
        // 根据秒数转换成对应的时分秒
        getHMS (time) {
            if(!time){
                return '00:00:00';
            }
            const hour = parseInt(time / 3600) < 10 ? '0' + parseInt(time / 3600) : parseInt(time / 3600);
            const min = parseInt(time % 3600 / 60) < 10 ? '0' + parseInt(time % 3600 / 60) : parseInt(time % 3600 / 60);
            const sec = parseInt(time % 3600 % 60) < 10 ? '0' + parseInt(time % 3600 % 60) : parseInt(time % 3600 % 60);
            return hour + ':' + min + ':' + sec;
        }
    },
    created() {
        this.getOldCheckState();
    },
    computed:{
        // 当前选中的表格id集合
        selectIds() {
            return this.selectItems.map((i) => i.resourceId);
        }
    },
    methods: {
        /**
         * 资源现在的审核状态
         */
        getOldCheckState() {
            const path = this.$route.path;
            const page = path.substring(path.lastIndexOf("/")+1);
            // W:待审核、P:审核通过、N:审核不通过
            const oldCheckStates = {
                "search":'P',
                "wait":'W',
                "fail": 'N'
            };
            this.oldCheckState = oldCheckStates[page];
        },
        /**
         * 删除资源
         * @param {String} resource 资源
         */
         onDelete(resource) {
            this.isShowDeleteLoading = true;
            // 判断资源是否在使用
            return Promise.allSettled([coursewareApi.getResourceStatus({
                resourceId: resource.resourceId
            }), new Promise((resolve, reject) => {
                ccApi.queryResourceIsUse({
                    data: {
                        resourceId: resource.resourceId
                    },
                    success: resolve,
                    fail: reject,
                    error: reject,
                });
            })]).then(([stsRes, useRes]) => {
                const { value : stsValue } = stsRes;
                const { value : useValue } = useRes;
                console.warn(stsValue, useValue);
                if (stsValue || useValue) { // 1资源在使用
                    this.resourceId = resource.resourceId;
                    this.dialog.isShowDeleteDialog = true;
                    this.dialog.isShowDeleteDialogResourceTip = useValue;
                    this.dialog.isShowDeleteDialogCardTip = stsValue;
                } else {// 2资源没有在使用
                    this.deleteResource(resource.resourceId, resource.applyScope);
                }
            }).catch((err) => {
                console.warn(err);
            }).finally(() => {
                this.isShowDeleteLoading = false;
            });
        },
        /**
         * 资源没有使用时-删除资源
         * @param {String} resourceId 资源id
         */
        deleteResource(resourceId) {
            this.$confirm('删除后，资源及所编辑信息均会删除,且不可恢复?', '删除提醒', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.isShowDeleteLoading = true;
                coursewareApi.deleteResource({
                    data: {
                        resourceId,
                        applyScope: 'C'//Q:题 C:课 H:讲义
                    },
                    success: () => {
                        this.$message.success('删除操作成功');
                        this.onSubmit();
                    },
                    complete: () => {
                        this.isShowDeleteLoading = false;
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        /**
         * 根据项目id获取系列课
         * @param projectId
         * @param teachRange
         * @returns
         */
        getSeriesCourse(projectId, teachRange) {
            this.$set(this.$refs.quickScreenRef.quickParams, 'seriesCourseId', '');
            let quickList = this.quickList;
            let quickIndex = quickList.findIndex( item => item.key === 'teachRange');
            let subindex = quickList.findIndex( item => item.key === 'seriesCourseId');
            if(!teachRange) {// 点击的是教学阶段-全部
                if(subindex !== -1) {//将系列课从列表中删除
                    quickList.splice(subindex, 1);
                }
                this.quickList = quickList;
                return;
            }
            rcTagApi.queryCoursesTreeList({
                data: {
                    projectId
                },
                success: (result) => {
                    let series =  result.find(item=> item.teachRangeCode === teachRange);
                    if(series) {
                        const seriesList = series.seriesCourses.map( item => ({
                            name: item.name,
                            code: item.id
                        }));
                        if(subindex===-1) {//显示系列课
                            quickList.splice(quickIndex + 1, 0,
                                {
                                    quickName:'系列课',
                                    key: 'seriesCourseId',
                                    type: 'H',
                                    enumData: seriesList
                                }
                            );
                        } else { //更新系列课数据
                            quickList[subindex].enumData = seriesList;
                        }
                    } else {
                        if(subindex!==-1) {
                            quickList[subindex].enumData = [];
                        }
                    }
                    this.quickList = quickList;
                }
            });
        },
        /**
         * 审核资源
         * @param {String} resourceId 资源id
         * @param {boolean} isEdit 编辑界面的审核通过
         */
         handleAudit(resourceId,isEdit) {
            if( isEdit) {
                this.checkResourceVideoPass(resourceId,isEdit);
            } else {
                this.$confirm('确认审核通过?', '审核提醒', {
                    confirmButtonText: '审核通过',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                   this.checkResourceVideoPass(resourceId,isEdit);
                });
            }

        },
        /**
         * 审核通过资源
         * @param {String} resourceId 资源id
         * @param {boolean} isEdit 编辑界面的审核通过
         */
        checkResourceVideoPass(resourceId,isEdit) {
            if(isEdit) {
                this.editMixin_AuditLoading = true;
            }
            coursewareApi.checkResourceVideo({
                data: {
                    resourceId: resourceId,
                    checkState: 'P',
                    oldCheckState: this.oldCheckState
                },
                success: () => {
                    this.$message.success('已审核通过');
                    this.onSubmit();
                    this.editMixin_isShowEditDialog = false;
                },
                complete: () => {
                    if(isEdit) {
                        this.editMixin_AuditLoading = false;
                    }

                }
            });
        },
         /**
         * 关闭日志弹窗
         */
          closeLogDialog(){
            this.resourceId = '';
            this.dialog.isShowLogDialog = false;
        },
        /**
         * 查看日志
         * @param {String} resourceId 资源id
         */
        onSearchLog(resourceId) {
            this.resourceId = resourceId;
            this.dialog.isShowLogDialog = true;
        },
        /**
         * 跳转到预览课件页面
         * @param {String} resourceId 资源id
         */
        onPreview(resourceId) {
            const path = this.$route.path;
            const page = path.substring(path.lastIndexOf("/")+1);
            if(page==='qc'){//质检页面
                nlapp.PageUtil.openNewWindow('/rc/courseware-preview-batch', {
                    ids: [resourceId],
                });
            }else{
                nlapp.PageUtil.navigateToOnly('/rc/courseware/preview', {
                    id: resourceId,
                    pageIndex: this.resourceQueryPagination.pageIndex
                });
            }

        },
        //质检页面-批量预览
        onBatchPreview(){
            if (!this.selectIds.length) {
				this.$message.warning("请先选择课件!");
				return;
			}
            if (this.selectIds.length > 9) {
				this.$message.warning("一次最多只能选择9个课件!");
				return;
			}
            nlapp.PageUtil.openNewWindow('/rc/courseware-preview-batch', {
                ids: this.selectIds,
            });
        },
        /**
         * 替换课件
         * @param {string} resourceId 原视频资源标识
         */
        onClickReplace(resourceId) {
            this.resourceId = resourceId;
            this.dialog.isShowReplaceDialog = true;
        },
        closeReplaceDialog() {
            this.oldVideoVid = '';
            this.dialog.isShowReplaceDialog = false;
        },
        /**
         * 全选按钮
         * @param val
         */
         oncheckallchange(val) {
            this.isCheckedAll = val;
            if (val) {
                this.resourceList.forEach(item => {
                    this.$refs.table.toggleRowSelection(item,true);
                });
                this.selectItems = this.resourceList;
            } else {
                this.selectItems = [];
                this.$refs.table.clearSelection();
            }
        },
        // 表格选中项改变
		selectionChange(arr) {
			this.selectItems = arr;
            this.isCheckedAll = this.resourceList.length && arr.length === this.resourceList.length;
		},
         /**
         * 关闭删除弹窗
         */
        closedeleteDialog(){
            this.resourceId = '';
            this.dialog.isShowDeleteDialog = false;
        },
         /**
         * 批量删除
         */
        onBatchDelete() {
            if (!this.selectIds.length) {
				this.$message.warning("请先选择课件!");
				return;
			}
            this.$confirm('资源删除后，将不可恢复，确定删除?', '删除提醒', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.isShowBatchDeleteLoading = true;
                coursewareApi.batchDeleteResource({
                    data: {
                        resourceIds: this.selectIds
                    },
                    success: () => {
                        this.$message.success('批量删除成功!');
                        this.onSubmit();
                    },
                    complete: () => {
                        this.isShowBatchDeleteLoading = false;
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });

        },
        // 批量导出
		exportResource() {
			if (!this.selectIds.length) {
				this.$message.warning("请先选择资源");
				return;
			}
            this.isShowExportLoading = true;
			coursewareApi.exportResource({
				data: {
					resourceIds: this.selectIds
				},
				success: ({ exportFilePath }) => {
                    const filePath = niceloo.path.getServerFileDownloadPath(exportFilePath);
                    window.open(filePath);
				},
                complete: () => {
                    this.isShowExportLoading = false;
                }
			});
		},
        // 跳转到资源使用详情
        onResourceDetail(resourceId) {
            nlapp.PageUtil.navigateToOnly('/rc/courseware/relevance-detail', {
                id: resourceId,
                pageIndex: this.pageIndex
            });
            this.onCloseDialog();
        },
        /**
         * 年倒序排序
         */
        sortYear(yearList) {
            return yearList.sort( (m, n) => n.projectyearYear - m.projectyearYear);
        },
        /**
         * 复制文本
         * @param {String} text 复制的文本信息
         */
         toCopy(text) {
            if (StringUtil.copyText(text)) {
                this.$message.success("复制成功");
            } else {
                this.$message.error("复制失败");
            }
        },
        formatDateNow(date) {
            date = new Date(date);
            let Y = date.getFullYear() + '-';
            let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            let D = (date.getDate() + '').padStart(2, '0');
            return Y + M + D;
        },
        formatDateStart(date) {
            date = new Date(date);
            let Y = date.getFullYear() + '-';
            let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            let D = (date.getDate() + '').padStart(2, '0');
            return Y + M + D;
        },
        formatDateEnd(date) {
            date = new Date(date);
            let Y = date.getFullYear() + '-';
            let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            let D = (date.getDate() + '').padStart(2, '0');
            return Y + M + D;
        },
        beforeWeek() {
            let date = +new Date() - 1000 * 60 * 60 * 24 * 7;
            return new Date(date);
        },
        beforeMonth() {
            let date = +new Date() - 1000 * 60 * 60 * 24 * 30;
            return new Date(date);
        },
        beforeYear() {
            let date = +new Date() - 1000 * 60 * 60 * 24 * 365;
            return new Date(date);
        }
    },
};
